<?php


namespace App\backend\services;

use App\backend\models\MemberGroupModel;
use App\Exceptions\InvalidRequestException;

class MemberGroupServices
{

    /**
     * 列表
     */
    public function list($request)
    {
        return MemberGroupModel::query()
            // 搜索
            ->when($group_name = $request['group_name']??'', function ($query) use ($group_name) {
                $query->where('group_name', 'like', '%' . $group_name . '%');
            })
            ->paginate($request->limit??10);
    }

    /**
     * 详情
     */
    public function details($request)
    {
        if (!$data = MemberGroupModel::query()->where('id',$request['id'])->first()){
            throw new InvalidRequestException(10009);
        }
        return $data;
    }

    /**
     * 添加
     */
    public static function addGroup($request)
    {
        $data = [
            'group_name' => $request['group_name'], // 会员分组名称
            'automatic_labeling' => $request['automatic_labeling'], // 自动打标签
            'accumulated_transaction_amount' => $request['accumulated_transaction_amount'], // 累计交易金额
            'accumulated_transaction_orders' => $request['accumulated_transaction_orders'], // 累计交易订单
            'current_points_greater' => $request['current_points_greater'], // 当前积分大于
            'current_balance' => $request['current_balance'], // 当前余额大于
            'goods_ids' => $request['goods_ids'], // 购买指定商品id
            'created_at' => time(),
        ];
        return MemberGroupModel::query()->insert($data);
    }

    /**
     * 编辑
     */
    public static function editGroup($request)
    {
        if (!MemberGroupModel::query()->where('id',$request['id'])->first()){
            throw new InvalidRequestException(10009);
        }
        $data = [
            'group_name' => $request['group_name'], // 会员分组名称
            'automatic_labeling' => $request['automatic_labeling'], // 自动打标签
            'accumulated_transaction_amount' => $request['accumulated_transaction_amount'], // 累计交易金额
            'accumulated_transaction_orders' => $request['accumulated_transaction_orders'], // 累计交易订单
            'current_points_greater' => $request['current_points_greater'], // 当前积分大于
            'current_balance' => $request['current_balance'], // 当前余额大于
            'goods_ids' => $request['goods_ids'], // 购买指定商品id
            'updated_at' => time(),
        ];
        return MemberGroupModel::query()->where('id',$request['id'])->update($data);
    }

    /**
     * 删除
     */
    public static function deleteGroup($request)
    {
        if (!MemberGroupModel::query()->where('id',$request['id'])->first()){
            throw new InvalidRequestException(10009);
        }
        return MemberGroupModel::query()->where('id',$request['id'])->delete();
    }

}
